/* This code shows how to add elements to an array list and 
 * how to iterate through them using iterator
 */
package com.vishu.collections;

import java.util.*;
public class ArrayListIterators {
	
	public static void main(String[] args) {
		
		ArrayList<String> al=new ArrayList<String>();
		
		al.add("vishu0");
		al.add("vishu1");
		al.add("vishu2");
		al.add("vishu3");
		
		// ITERATOR TO PRINT ELEMENTS IN FORWARD DIRECTION	
		System.out.println("With simple iterator which prints only in forward direction:");
		
		//get iterator
		Iterator<String> itr=al.iterator();
		
		//iterate through list elements
		while(itr.hasNext()){
			String element= itr.next();			
			System.out.println(element);
		}
		System.out.println();
				
		//REMOVING AN ELEMENT USING ITERATOR
		itr=al.iterator();
		while(itr.hasNext()){
			
			/* Remove method removes an element from underlying collection and
	           it may throw a UnsupportedOperationException if the remove
	           operation is not supported.
	         */
			
			if(itr.next().equals("vishu2")){
				System.out.println(" --removing vishu2");
				itr.remove();
			}
			
		}
		System.out.println();
		
		//LISTITERATOR TO PRINT ELEMENTS IN FORWARD DIRECTION		
		ListIterator<String> litr=al.listIterator(); 
		System.out.println("List elements after removing vishu2:");
		while(litr.hasNext()){
			
			System.out.println(litr.next());
		}
		System.out.println();
		
		//MODIFY ELEMENTS OF LIST USING LISTITERATOR
		litr=al.listIterator();
		System.out.println(" --modifying the elements of List using list iterator");
		while(litr.hasNext())
		{
			
			String element=litr.next();
			litr.set(element+"- modified");
			//Also we can use litr.remove to remove any element
			
		}
		System.out.println();
		
		//LISTITERATOR TO PRINT MODIFIED ELEMENTS 
		System.out.println("List elements after modification:");
		litr=al.listIterator();
		while(litr.hasNext()){
			
			System.out.println(litr.next());
			
		}
		System.out.println();
		
		//LISTITERATOR TO PRINT MODIFIED ELEMENTS IN BACKWARD DIRECTION 
		//since litr pointer at the end now, we can directly use hasPrevious method.
		System.out.println("List elements in reverse direction after modification:");
		while(litr.hasPrevious()){
			
			System.out.println(litr.previous());
			
		}
				
				
		
	}



}
